﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;
namespace LabMS.Web.OpenProject
{
    public partial class openprojectperview : Base.BasePage
    {
        public string strID = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            strPagePrivilege.Add("KFSYGL");//必须写在ispostback外
            strPageUserType.Add("mana");
            strPageUserType.Add("teacher");

            if (Request.QueryString["id"] == null)
            {
                Common.JShelper.JSAlert(Page, "err", "参数错误!");
                return;
            }
            if (Request.QueryString["where"] != null)
            {
                tbWhere.Value = "0";
            }
            strID = Request.QueryString["id"].ToString();
            if (!Page.IsPostBack)
            {

                LabMS.Model.OpentProject mopproject = checkQueryString(strID);
                if (mopproject == null)
                {
                    Common.JShelper.JSAlert(Page, "err2", "开放实验项目不存在!");
                    return;
                }
                
                bind(mopproject);
                iniBtn(mopproject.OP_Audit);
                bindDDL(mopproject);

                Gv_File_DataBind();

                lbPageName.Text = mopproject.OP_ProjectName + "详情";
                lbCID.Text = mopproject.ID.ToString();
                tbID.Value = mopproject.ID.ToString();

            }
            this.Page.Title = lbPageName.Text;

        }

        void iniBtn(string strStatus)
        {
            btnApp.Visible = false;
            btnDel.Visible = false;
            btnEdit.Visible = false;
            btnCancelApp.Visible = false;
            tbnCheck.Visible = false;
            tbnUnChek.Visible = false;

            if (strStatus == "0")
            {
                btnApp.Visible = true;
                btnDel.Visible = true;
                btnEdit.Visible = true;
            }
            if (strStatus == "1")
            {
                btnCancelApp.Visible = true;
                tbnCheck.Visible = true;
                tbnUnChek.Visible = true;
                paneltoCheck.Visible = true;
            }
            if (strStatus == "2")
            {
                btnEdit.Visible = true;
                btnDel.Visible = true;
            }
            if (strStatus == "3")
            {
                btnDel.Visible = true;
                panelExamine.Visible = true;
            }
        }

        LabMS.Model.OpentProject checkQueryString(string strID)
        {
            LabMS.BLL.OpentProject bopproject = new LabMS.BLL.OpentProject();
            string strWhere = "ID =" + strID;
            List<LabMS.Model.OpentProject> listmopproject = bopproject.GetModelList(strWhere);
            if (listmopproject.Count == 0)
            {
                return null;
            }
            return listmopproject[0];
        }

        public void bindDDL(LabMS.Model.OpentProject mopproject)
        {
            LabMS.BLL.Lab blab = new LabMS.BLL.Lab();
            List<LabMS.Model.Lab> mLab = new List<LabMS.Model.Lab>();
            mLab = blab.GetModelList(" Lab_ParentID is null ");
            ddlLabName.DataSource = mLab;
            ddlLabName.DataTextField = "Lab_Name";
            ddlLabName.DataValueField = "Lab_Code";
            ddlLabName.DataBind();
            ddlLabName.SelectedValue = mopproject.Project_Lab;

            ExtendBLL.Dictionary eDictionary = new ExtendBLL.Dictionary();
            List<Model.Dictionary> listCClass = new List<LabMS.Model.Dictionary>();


            listCClass = eDictionary.GetItemListByDClass("shiyanleibie");
            ddlProjectCategory.DataSource = listCClass;
            ddlProjectCategory.DataTextField = "Name";
            ddlProjectCategory.DataValueField = "Code";
            ddlProjectCategory.DataBind();
            ddlProjectCategory.SelectedValue = mopproject.Project_Category;

            listCClass = eDictionary.GetItemListByDClass("shiyanleixing");
            ddlProjectType.DataSource = listCClass;
            ddlProjectType.DataTextField = "Name";
            ddlProjectType.DataValueField = "Code";
            ddlProjectType.DataBind();
            ddlProjectType.SelectedValue = mopproject.Project_Type;

            listCClass = eDictionary.GetItemListByDClass("shiyanyaoqiu");
            ddlProjectRequire.DataSource = listCClass;
            ddlProjectRequire.DataTextField = "Name";
            ddlProjectRequire.DataValueField = "Code";
            ddlProjectRequire.DataBind();
            ddlProjectRequire.SelectedValue = mopproject.Project_Require;

            listCClass = eDictionary.GetItemListByDClass("shiyanzheleibie");
            ddlProjectPartnerType.DataSource = listCClass;
            ddlProjectPartnerType.DataTextField = "Name";
            ddlProjectPartnerType.DataValueField = "Code";
            ddlProjectPartnerType.DataBind();
            ddlProjectPartnerType.SelectedValue = mopproject.Project_PartnerType;

            listCClass = eDictionary.GetItemListByDClass("shiyanxiangmulaiyuan");
            ddlProjectComFrom.DataSource = listCClass;
            ddlProjectComFrom.DataTextField = "Name";
            ddlProjectComFrom.DataValueField = "Code";
            ddlProjectComFrom.DataBind();
            ddlProjectComFrom.SelectedValue = mopproject.OP_ProSource;

            LabMS.Model.SysSetting msys = new LabMS.Model.SysSetting();
            ExtendBLL.SysSetting extendsys = new ExtendBLL.SysSetting();
            msys = extendsys.GetCurrentSetting();
            List<string> listYear = Common.GradeHelper.GetCurrentGrade((int)msys.CurrentYear, (int)msys.CurrentSemester, false);
            ddlOPGrade.DataSource = listYear;
            ddlOPGrade.DataBind();
            ddlOPGrade.Items.Insert(0, new ListItem("", "0"));
            ddlOPGrade.SelectedValue = mopproject.OP_Grade;

            ddlOPFunds.SelectedValue = mopproject.OP_Funds;

            if (mopproject.SYear != msys.CurrentYear || mopproject.Semester != msys.CurrentSemester)
            {
                btnApp.Visible = false;
                btnDel.Visible = true;
                btnEdit.Visible = false;
                btnCancelApp.Visible = false;
                tbnCheck.Visible = false;
                tbnUnChek.Visible = false;
                tbCurrent.Value = "0";
                paneltoCheck.Visible = false;
                panelExamine.Visible = false;
            }
        }

        void bind(LabMS.Model.OpentProject mopproject)
        {
            tbOPContent.Text = mopproject.OP_OpenType;
            tbOPInCharge.Text = mopproject.OP_InCharge;
            tbOPPhone.Text = mopproject.OP_Phone;
            tbOPPlanningCourseTime.Text = mopproject.OP_PlanningCourseTime;
            tbOPProfessioanl.Text = mopproject.OP_Professioanl;
            tbOPReason.Text = mopproject.OP_AppIntro;
            tbProjectCode.Text = mopproject.OP_ProjectCode;
            tbProjectEndWeek.Text = mopproject.Project_EndWeek.Value.ToString();
            tbProjectName.Text = mopproject.OP_ProjectName;
            tbProjectStartWeek.Text = mopproject.Project_StartWeek.Value.ToString();

            ExtendBLL.Dictionary eDictionary = new ExtendBLL.Dictionary();
            List<Model.Dictionary> listCClass = new List<LabMS.Model.Dictionary>();
            listCClass = eDictionary.GetModelList(" DClass='xueke' and Code ='" + mopproject.Project_Subject + "'");
            if (listCClass.Count > 0)
            {
                tbProjectSubjectCode.Text = listCClass[0].Name;
            }

            LabMS.BLL.Teacher bteacher = new LabMS.BLL.Teacher();
            List<Model.Teacher> listteacher = new List<LabMS.Model.Teacher>();
            listteacher = bteacher.GetModelList(" Teacher_Code ='" + mopproject.OP_Teacher + "'");
            if (listteacher.Count > 0)
            {
                tbTeacherCode.Text = listteacher[0].Teacher_Name;
            }


            tbTeacherCode.Text = mopproject.OP_Teacher;
            lbAppDate.Text = mopproject.OP_AppTime.Value.ToShortDateString();
            lbAppPerson.Text = mopproject.OP_Applicant;
            lbOP_Approval.Text = mopproject.OP_Approval;
            string strSemester = Common.Status.GetSemester(mopproject.Semester.Value);
            lbSTime.Text = mopproject.SYear.Value.ToString() + "学年 " + strSemester;
            string strStatus = Common.Status.GetOpenProjectStatus(mopproject.OP_Audit);
            lbStatus.Text = strStatus;
            ExtendBLL.ProjectAppointment eprojectapp = new ExtendBLL.ProjectAppointment();
            List<LabMS.Model.Student> listStudent = new List<LabMS.Model.Student>();
            listStudent = eprojectapp.GetStudentByProject(mopproject.OP_ProjectCode);
            gv_studentList.DataSource = listStudent;
            gv_studentList.DataBind();
            if (mopproject.OP_Audit == "2" || mopproject.OP_Audit == "3")
            {
                panelExamine.Visible = true;
                lbAuditOpinion.Text = mopproject.AuditOpinion;
                lbCheckTime.Text = mopproject.CheckTime.Value.ToShortDateString();
            }
        }

        protected void btnApp_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            string strAudit = "";
            string strAlert = "";
            if (btn.ID == "btnCancelApp")
            {
                strAudit = "0";
                strAlert = "撤销申请成功!";
            }
            if (btn.ID == "btnApp")
            {
                strAudit = "1";
                strAlert = "申请成功,请等待审核!";
            }
            if (btn.ID == "tbnCheck")
            {
                strAudit = "3";
                strAlert = "审核成功!";
            }
            if (btn.ID == "tbnUnChek")
            {
                strAudit = "2";
                strAlert = "审核成功!";
            }
            ExtendBLL.OpentProject extendopproject = new ExtendBLL.OpentProject();
            string strID = lbCID.Text;
            try
            {
                if (btn.ID == "btnApp" || btn.ID == "btnCancelApp")
                {
                    extendopproject.UpdateStatus(strAudit, strID);
                }
                else
                {
                    string strChecker = "";//用户名
                    string strCheckContent = tbCheckContent.Text.Trim();
                    extendopproject.SetCheck(strAudit, strID, DateTime.Today.ToShortDateString(), strChecker, strCheckContent);
                }
            }
            catch (Exception ex)
            {
                lbErr.Text = ex.Message;
                lbErr.Visible = true;
                return;
            }
            if (tbWhere.Value == "1")
            {
                Common.JShelper.JSAlertAndRedirect(Page, "success", strAlert, "openprojectperview.aspx?ID=" + strID);
            }
            else if (tbWhere.Value == "0")
            {
                Common.JShelper.JSAlertAndRedirect(Page, "success", strAlert, "openprojectperview.aspx?ID=" + strID + "&where=0");
            }
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            ExtendBLL.OpentProject extendopproject = new ExtendBLL.OpentProject();
            string strID = lbCID.Text;
            string strAlert = "删除成功!";
            try
            {
                extendopproject.Delete(int.Parse(strID));
            }
            catch (Exception ex)
            {
                lbErr.Text = ex.Message;
                lbErr.Visible = true;
                return;
            }
            if (tbWhere.Value == "1")
            {
                Common.JShelper.JSAlertAndRedirect(Page, "success", strAlert, "currentopenprojectlist.aspx");
            }
            else if (tbWhere.Value == "0")
            {
                Common.JShelper.JSAlertAndRedirect(Page, "success", strAlert, "openprojectlist.aspx");
            }
        }

        protected string GetItemType(object value) 
        {
            if (value != null) 
            {
                string v = value.ToString();
                switch (v) 
                {
                    case "3":
                        return "开放实验申请书";
                }
            }
            return "";
        }


        protected void Gv_File_DataBind() 
        {
            if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                if (IsNumber(Request.QueryString["ID"].Trim()))
                {
                    int num=0;
                    if (int.TryParse(Request.QueryString["ID"].Trim(), out num))
                    {
                        LabMS.BLL.AttachmentItem AttachmentItem = new LabMS.BLL.AttachmentItem();
                        List<LabMS.Model.AttachmentItem> ls = new List<LabMS.Model.AttachmentItem>();
                        LabMS.Model.OpentProject openprojectmodel = new LabMS.Model.OpentProject();
                        LabMS.BLL.OpentProject OpenProject = new LabMS.BLL.OpentProject();
                        openprojectmodel= OpenProject.GetModel(num);
                        if (openprojectmodel != null) 
                        {
                            if (openprojectmodel.Attachment != null) 
                            {
                                ls = AttachmentItem.GetModelList("Attach_ID=" + openprojectmodel.Attachment);
                                
                            }
                        }
                        Gv_File.DataSource = ls;
                        Gv_File.DataBind();
                    }
                }
            }
            
        }


        protected bool IsNumber(String strNumber)
        {
            Regex objNotNumberPattern = new Regex("[^0-9.-]");
            Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");
            Regex objTwoMinusPattern = new Regex("[0-9]*[-][0-9]*[-][0-9]*");
            String strValidRealPattern = "^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
            String strValidIntegerPattern = "^([-]|[0-9])[0-9]*$";
            Regex objNumberPattern = new Regex("(" + strValidRealPattern + ")|(" + strValidIntegerPattern + ")");

            return !objNotNumberPattern.IsMatch(strNumber) && !objTwoDotPattern.IsMatch(strNumber) && !objTwoMinusPattern.IsMatch(strNumber) && objNumberPattern.IsMatch(strNumber);
        }

        protected void Gv_File_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "DownLoad") 
            {
                FileItemDownload(int.Parse(Gv_File.DataKeys[int.Parse(e.CommandArgument.ToString())].Values["ID"].ToString()), Gv_File.DataKeys[int.Parse(e.CommandArgument.ToString())].Values["Item_Address"].ToString(), Gv_File.DataKeys[int.Parse(e.CommandArgument.ToString())].Values["Item_Name"].ToString());
            }
        }


        private void FileItemDownload(int  itemID,string Item_Address,string Item_Name)
        {
           
            if (itemID == 0)
            {
                lbErr.Text = "附件参数错误";
                return;
            }

            
            System.IO.Stream iStream = null;
            try
            {
                string fullpath = Server.MapPath("../" + Item_Address);

                if (System.IO.File.Exists(fullpath))
                {

                    Response.Clear();
                    Response.Charset = "UTF-8";
                    Response.Buffer = true;
                    Response.ContentEncoding = System.Text.Encoding.UTF8;
                    Response.HeaderEncoding = System.Text.Encoding.UTF8;

                  
                    byte[] buffer = new byte[100000];
                    int iLength;
                    long dataToRead;
                    iStream = new FileStream(fullpath, FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
                    dataToRead = iStream.Length;

                    Response.ContentType = "application/octet-stream";
                    string fileName = Item_Name;
                    string nameTemp = "";
                    HttpBrowserCapabilities br = HttpContext.Current.Request.Browser;
                    if (br.Browser == "IE")
                    {
                        nameTemp = HttpUtility.UrlEncode(fileName);
                        nameTemp = nameTemp.Replace("+", "%20");
                        Response.AppendHeader("Content-Disposition", "attachment;filename=" + nameTemp);
                    }
                    else
                    {
                        nameTemp = fileName.Replace(" ", "");
                        Response.AppendHeader("Content-Disposition", "attachment; filename=" + nameTemp);
                    }

                    while (dataToRead > 0)
                    {
                        if (Response.IsClientConnected)
                        {
                            iLength = iStream.Read(buffer, 0, 100000);
                            Response.BinaryWrite(buffer);
                            Response.Flush();
                            buffer = new byte[100000];
                            dataToRead = dataToRead - iLength;
                        }
                        else
                        {
                            dataToRead = -1;
                        }
                    }

                }
                else
                {
                    throw new Exception("不存在该文件");
                }


            }
            catch (Exception ex)
            {
                lbErr.Text = ex.Message;

            }
            finally
            {
                if (iStream != null)
                {
                    iStream.Close();
                }
            }
        }



    }
}
